import axios from 'axios'
import type {
  AxiosInstance,
  AxiosResponse,
  AxiosError,
  InternalAxiosRequestConfig,
} from 'axios'
import { useEnv } from '@/hooks/useEnv'
import { getToken } from '@/utils/auth'
import C from '@/constants'
// import { AxiosLoading } from '@/config/loading'
// const axiosLoading = new AxiosLoading()

const { VITE_BASE_API } = useEnv()
const service: AxiosInstance = axios.create({
  baseURL: VITE_BASE_API, // 环境变量
  timeout: 30000, // 请求超时时间
  withCredentials: true, // 是否允许携带cookie
  headers: { 'Content-Type': 'application/json;charset=UTF-8' },
})

// 请求拦截器
service.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  const token = getToken()
  if (token) {
    config.headers.Authorization = token
  }

  // axiosLoading.addLoading()
  return config
})

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    return response.data
  },
  (err) => {
    // axiosLoading.closeLoading()
    return Promise.reject(err.response)
  }
)
// 公共请求方法
const request = {
  get<T = any>(url: string, data?: any, responseType?: any): Promise<T> {
    return request.request(
      C.RequestEnum.GET,
      url,
      { params: data },
      responseType
    )
  },
  post<T = any>(url: string, data?: any): Promise<T> {
    return request.request(C.RequestEnum.POST, url, { data })
  },
  put<T = any>(url: string, data?: any): Promise<T> {
    return request.request(C.RequestEnum.PUT, url, { data })
  },
  delete<T = any>(url: string, data?: any): Promise<T> {
    return request.request(C.RequestEnum.DELETE, url, { params: data })
  },
  request<T = any>(
    method = C.RequestEnum.GET,
    url: string,
    data?: any,
    responseType?: string
  ): Promise<T> {
    return new Promise((resolve, reject) => {
      service({ method, url, ...data, responseType })
        .then((res) => {
          resolve(res as unknown as Promise<T>)
        })
        .catch((e: Error | AxiosError) => {
          reject(e)
        })
    })
  },
}

export default request
